<?php
class ModelCatalogAttribute extends Model {
	public function addAttribute($data) {
        $is_color_group = isset($data['is_color_group']) ? $data['is_color_group'] : 0;
		$this->db->query("INSERT INTO " . DB_PREFIX . "attribute SET name = '" . $this->db->escape($data['name']) . "', description = '" . $this->db->escape($data['description']) . "', sort_order = '" . $this->db->escape($data['sort_order']) . "', date_added = NOW(), date_modified = NOW()" . ", status = '" . (int)$data['status'] . "', is_color_group = '" . $is_color_group . "'");
        $attribute_id = $this->db->getLastId();
        if(isset($data['attribute_values'])){
            $this->addAttributeValues($attribute_id, $data['attribute_values']);
        }
        
		$this->cache->delete('attribute');
	}
	
	public function editAttribute($attribute_id, $data) {
        $is_color_group = isset($data['is_color_group']) ? $data['is_color_group'] : 0; 
        $current = $this->getAttribute($attribute_id);
		
        $this->db->query("UPDATE " . DB_PREFIX . "attribute SET name = '" . $this->db->escape($data['name']) . "', description = '" . $this->db->escape($data['description']) . "', sort_order = '" . $this->db->escape($data['sort_order']) . "', date_modified = NOW()" . ", status = '" . (int)$data['status'] . "', is_color_group = '" . $is_color_group . "' WHERE attribute_id = '" . (int)$attribute_id . "'");
        if($this->db->escape($data['name']) != $current['name']){
            $option_data = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option WHERE attribute_id = '" . (int)$attribute_id . "'");
            $product_option = $option_data->rows;
            foreach($product_option as $option){
                $this->db->query("UPDATE " . DB_PREFIX . "product_option_description SET name = '" . $this->db->escape($data['name']) . "' WHERE product_option_id = '" . (int)$option['product_option_id'] . "'");    
            }
        }
        if(isset($data['attribute_values'])){
            $this->editAttributeValues($attribute_id, $data['attribute_values'], $is_color_group); 
        }
        
		$this->cache->delete('attribute');
	}
	
	public function deleteAttribute($attribute_id) {
		$this->deleteAttributeValues($attribute_id);
        $this->db->query("DELETE FROM " . DB_PREFIX . "attribute WHERE attribute_id = '" . (int)$attribute_id . "'");
        
		$this->cache->delete('attribute');        
	}

	public function getAttribute($attribute_id) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "attribute WHERE attribute_id = '" . (int)$attribute_id . "'");
	
		$data = $query->row;
        //$data['attribute_values'] = $this->getAttributeValues($attribute_id);
        
        return $data;
	}
    
    public function getColorAttributes() {
        $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "attribute WHERE is_color_group = '1'");    
        $data = $query->rows;        
        
        return $data;
    }
    
    public function getNormalAttributes() {
        $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "attribute WHERE IFNULL(is_color_group, 0) = 0");    
        $data = $query->rows;        
        
        return $data;
    }
    
    public function getAttributeValues($attribute_id, $order = '') {
        if($order == ''){
            $order = ' ORDER BY sort_order ASC';
        }
        else{
            $order = ' ORDER BY ' . $order . ' ASC';    
        }
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "attribute_value WHERE attribute_id = '" . (int)$attribute_id . "' " . $order);
    
        return $query->rows;
    }
	
    public function getAttributesWithValues() {
        $attributes =  $this->getNormalAttributes(); 
        foreach($attributes as &$item){
            $item['values'] = $this->getAttributeValues($item['attribute_id']);
        }        
        
        return $attributes;
    }
    
    public function addAttributeValues($attribute_id, $data){
        if(isset($data)){            
            foreach($data as $item) {               
                $this->db->query("INSERT INTO " . DB_PREFIX . "attribute_value SET attribute_id = '" . (int)$attribute_id . "', name = '" . $this->db->escape($item['name']) . "', sort_order = '" . (int)$item['sort_order'] . "', image = '" . $this->db->escape($item['image']) . "'");
            }                    
        }
    }
    
    public function editAttributeValues($attribute_id, $data, $is_color_group){  
        if(isset($data)){
            $this->db->query("DELETE FROM " . DB_PREFIX . "attribute_value WHERE attribute_id = '" . (int)$attribute_id . "'");
            usort($data, 'compare_id');  
            foreach ($data as $item) {  
                $color = $is_color_group ? "', image = '" . $item['image'] : '';
                $value_id = ($item['value_id'] > 0) ? "', value_id = '" . (int)$item['value_id'] : '';
                $query = "INSERT INTO " . DB_PREFIX . "attribute_value SET attribute_id = '" . (int)$attribute_id . "', name = '" . $this->db->escape($item['name']) . "', sort_order = '" . (int)$item['sort_order'] . $color . $value_id . "'"; 
                $this->db->query($query);   
                                
                $option_data = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value WHERE attribute_value_id = '" . (int)$item['value_id'] . "'");
                $product_option = $option_data->rows;  
                foreach($product_option as $option){
                    $this->db->query("UPDATE " . DB_PREFIX . "product_option_value_description SET name = '" . $this->db->escape($item['name']) . "' WHERE product_option_value_id = '" . (int)$option['product_option_value_id'] . "'");    
                }  
            }                    
        }    
    }
    
    public function deleteAttributeValues($attribute_id){
        $this->db->query("DELETE FROM " . DB_PREFIX . "attribute_value WHERE attribute_id = '" . (int)$attribute_id . "'");   
    }
    
    public function canDelete($attribute_id){
       $data = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value WHERE attribute_id = '" . (int)$attribute_id . "'");       
        
       return empty($data->rows);
    }
    
	public function getAttributes($data = array()) {
		if ($data) {
			$sql = "SELECT * FROM " . DB_PREFIX . "attribute";

			$sort_data = array(
				'name',
				'sort_order',
				'date_modified'
			);	
			
			if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
				$sql .= " ORDER BY " . $data['sort'];	
			} else {
				$sql .= " ORDER BY name";	
			}
			
			if (isset($data['order']) && ($data['order'] == 'DESC')) {
				$sql .= " DESC";
			} else {
				$sql .= " ASC";
			}
			
			if (isset($data['start']) || isset($data['limit'])) {
				if ($data['start'] < 0) {
					$data['start'] = 0;
				}				

				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}	
			
				$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
			}
			
			$query = $this->db->query($sql);             
                
			return $query->rows;
		} 
        else {
			$attribute_data = $this->cache->get('attribute');

			if (!$attribute_data) {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "attribute ORDER BY sort_order ASC");   	            
                $rows = $query->rows;
                /*
				foreach ($rows as $result) {
      				$attribute_data[] = array(
        				'attribute_id'  => $result['attribute_id'],
        				'name'          => $result['name'],
                        'date_modified' => $result['date_modified'],
        				'sort_order'    => $result['sort_order'],  						
						'status'        => $result['status'],                        					
      				);
    			}	
			
				$this->cache->set('attribute', $attribute_data);
                */
			}
			
			//return $attribute_data;	            
            return $query->rows;	
		}
	}	
    
    public function getTotalAttributes() {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "attribute");
        
        return $query->row['total'];
    }
}

function compare_id($a, $b){
    if(($a['value_id'] == 0) || ($b['value_id'] == 0)){
        return 1;    
    }
    
    // $a == $b    
    if($a['value_id'] == $b['value_id']){
        return 0;    
    }
    
    // $a < $b      
    if(($a['value_id'] < $b['value_id'])){
        return -1;  
    }   
    else{
        return 1;
    }
}
?>